package com.cp.yn

import android.content.Context
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.common.base.base.BaseApplication
import com.common.base.bean.ConfigBean
import com.common.base.common.SpecialModule
import com.common.base.http.main.ApiConfig
import com.common.base.manager.ConfigManager
import com.common.base.tools.utils.JsonUtils
import com.common.base.tools.utils.LifecycleBindOwner
import com.common.base.tools.utils.file.FileUtil
import com.common.base.tools.utils.file.StorageEnum
import com.common.base.tools.utils.logger
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Protocol
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import retrofit2.Invocation
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets



class MyApplication : BaseApplication() {

    override fun initConfig() {
        super.initConfig()
        ConfigManager.saveConfig(ConfigBean().apply {
            baseUrl = "http://10.10.12.133:888/"
            imageUrl = "http://img.yunatop.com/"
            local = ConfigManager.configBean?.local ?: "zh"
            fridge = "00001"
            isAllowOffline = true
        })

        ApiConfig.apply {
            log_path = "${FileUtil.getStorePath(StorageEnum.STORAGE_SDCARD)}/log"
            HTTP_TAG = "HTTP"
            isPrintHttpLog = true
            interceptorList = mutableListOf(RequestHeardInterceptor(),RsaInterceptor())
        }

        LifecycleBindOwner.instance().bindApp(object : DefaultLifecycleObserver {
            override fun onCreate(owner: LifecycleOwner) {
                super.onCreate(owner)
            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
            }
        })

    }

}



class RsaInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val invocation = request.tag(Invocation::class.java)
        var mSpecialModule =
            invocation?.method()?.getDeclaredAnnotation(SpecialModule::class.java)

        if (mSpecialModule != null && mSpecialModule.module.isNotEmpty()) {
            //命中加密注解
            if(mSpecialModule.module==SpecialModule.encryption) {
                //1、获取原始数据
                val response: Response
                try {
                    response = chain.proceed(request)
                } catch (e: Exception) {
                    throw e
                }
                val responseBody = response.body!!
                val source = responseBody.source()
                source.request(Long.MAX_VALUE) // Buffer the entire body.
                val buffer = source.buffer
                val contentLength = responseBody.contentLength()
                val contentType = responseBody.contentType()
                val charset: Charset =
                    contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
                if (contentLength != 0L) {
                    val readString = buffer.clone().readString(charset)
                    logger.info("原始数据:${JsonUtils.toJson(readString)}")

                    //2、解析加密 ---模拟数据
                    val testResponseString =
                        "{\"code\":200}"
                    val responseData = testResponseString.toByteArray()


                    logger.info("解密得到数据:${JsonUtils.toJson(testResponseString)}")
                    val responseNew =
                        Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200)
                            .message(mSpecialModule.module)
                            .body(responseData.toResponseBody("application/jsoncharset=utf-8".toMediaTypeOrNull()))
                            .build()
                    return responseNew
                }


            }
        }
        return chain.proceed(request)
    }

}


class RequestHeardInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val builder = originalRequest.newBuilder()
        builder.header("lang", ConfigManager.configBean?.local ?: "en")
        builder.header("token", UserManager.getToken())
        return chain.proceed(builder.build())
    }

}



